package top.malaoshi.service;

import org.springframework.stereotype.Service;
import top.malaoshi.dao.GoodsMapper;
import top.malaoshi.entity.Goods;
import top.malaoshi.redis.RedisUtil;

import javax.annotation.Resource;

@Service
public class GoodsSrvImpl {


    @Resource
    private GoodsMapper mapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 根据id查询商品详情
     *
     * 如果redis中读取出goods是null，就查询mysql，并放入到redis中
     * 如果根据id查询不到，说明不存在该商品，防止穿透，将value=-1放入redis中
     *
     * @param id 商品的id
     * @return 返回Goods类型
     */
    public Goods getById(String id){
        String redisKeyGoods="goods_"+id;
        String redisKeyGoodsLike="goods_like_"+id;
        //从redis中读取出goods信息
        Object goodsObj=redisUtil.get(redisKeyGoods);
        Goods res=null;

        if(goodsObj==null) {//如果redis中读取出goods是null，就查询mysql，并放入到redis中
            res = mapper.getById(id);
            if(res!=null) {
                if (res.getImgPath() == null) {
                    res.setImgPath("");
                }
                redisUtil.set(redisKeyGoods, res);

            }else{//如果根据id查询不到，说明不存在该商品，防止穿透，将value=-1放入redis中
                redisUtil.set(redisKeyGoods, "none");
            }
            redisUtil.expire(redisKeyGoods, 60 * 60 * 6);

        }else if("none".equals(goodsObj)){//如果redis中读取出goods是none，说明没有该记录，返回null
            res=null;
        }else{//如果redis中读取出goods有数据，从redis中读取出like，更新goods对象的like
            res=(Goods)goodsObj;
            Integer like=(Integer)redisUtil.get(redisKeyGoodsLike);
            if(like!=null){
                res.setLikeNum(like);
            }
        }

        return res;
    }

    /**
     * 点赞和取消点赞
     * @param id
     * @param num 大于0表示点赞，小于0表示取消点赞
     * @return
     */
    public int like(String id,int num){
        String redisKeyGoodsLike="goods_like_"+id;
        int like=0;
        if(num>0){
            like = (int) redisUtil.incr(redisKeyGoodsLike, num);
        }else{
            like = (int) redisUtil.decr(redisKeyGoodsLike, -num);
            if(like<0){
                like=0;
                redisUtil.set(redisKeyGoodsLike, 0);
            }
        }

        return like;
    }

}
